declare const wx: any

export class Utils {
  public static async findNext(score: number) {
    const rankData = await this.getRankData()
    const userGameData = await this.getUserInfo()
    for (let i = 0; i < rankData.length; i++) {
      const item = rankData[i]
      if (item.openid === userGameData.openid) {
        continue
      }
      if (score < item.score) {
        return item
      }
    }
    return null
  }

  private static rankData: Array<any> = null

  private static async getRankData() {
    if (!this.rankData) {
      const data: Array<any> = await this.getFriendCloudStorage();
      this.rankData = data.map(value => {
        return {
          score: parseInt(value.KVDataList[0].value),
          openid: value.openid,
          nickname: value.nickname,
          avatarUrl: value.avatarUrl
        }
      }).sort((a, b) => {
        return a.score - b.score
      })
    }
    return this.rankData

  }

  private static getFriendCloudStorage() {
    return new Promise((resolve, reject) => {
      wx.getFriendCloudStorage({
        keyList: ['score'],
        success(resp) {
          resolve(resp.data)
        },
        fail(err) {
          reject(err)
        },
      });
    })
  }

  public static loadRes(url: string): Promise<cc.SpriteFrame> {
    return new Promise<cc.SpriteFrame>((resolve, reject) => {
      let image = wx.createImage();
      image.onload = function () {
        let texture = new cc.Texture2D();
        texture.initWithElement(image);
        texture.handleLoadedTexture();
        resolve(new cc.SpriteFrame(texture));
      };
      image.src = url;
    })
  }

  private static userInfoCache = null

  public static getUserInfo(): Promise {
    return new Promise((resolve, reject) => {
      if (Utils.userInfoCache) {
        return resolve(Utils.userInfoCache)
      }
      wx.getUserInfo({
        success: function (res) {
          Utils.userInfoCache = res
          resolve(res)
        },
        fail: function (err) {
          reject(err)
        }
      })
    })
  }
}